import json
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

common_buff_api = Blueprint('common_buff_api', __name__)
common_buff_down_api = Blueprint('common_buff_down_api', __name__)

@common_buff_api.route("/common_buff", methods=['POST', 'GET'])
def project_action():
    params = json.loads(request.data)
    _action = params['action']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'view':
        reward_item_list = rewardList()
        reward_item_list = reward_item_list['name']

        query = CommonBuff.query.order_by('id').all()
        result = []
        for q in query:
            _buff = json.loads(q.buff)
            for i in range(len(_buff)):
                _buff[i] = {'a': [109, _buff[i]['a'][0], _buff[i]['a'][1]]}
            _buff = RewardShowToDoc(_buff, reward_item_list)
            tmp = {
                "id": int(q.id),
                'name': q.name,
                'buff': _buff
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'reward_list':
        doc_data = loadDocument()
        result_data = {}
        # buff
        item_type = 109
        result_data[item_type] = []
        for i in doc_data['doc_buff_info']:
            name = doc_data['doc_buff_info'][str(i)]['name']
            price = 100
            tmp = {}
            tmp['value'] = name + '-' + str(i)
            tmp['id'] = int(i)
            tmp['price'] = price
            result_data[item_type].append(tmp)
        result = {}
        result['reward'] = result_data

        return jsonify({'data': result['reward']})
    elif _action == 'delete':
        _id = params['id']
        project_data = CommonBuff.query.filter_by(id=_id).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = CommonBuff.query.filter_by(id=_id).first()
        if project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"
    elif _action == 'update':
        _data = params['list']
        for i in _data:
            for j in range(len(i['buff'])):
                i['buff'][j] = {'a': [i['buff'][j]['id'], i['buff'][j]['num']]}

        for i in _data:
            if i['id'] == -1:
                new_data = CommonBuff(
                    name=i['name'],
                    buff=json.dumps(i['buff']),
                )
                db.session.add(new_data)
            else:
                CommonBuff.query.filter_by(id=i['id']).update({
                    "name": i['name'],
                    "buff": json.dumps(i['buff'])
                })
        db.session.commit()
        result_data['data']['msg'] = '更新成功'
    return jsonify(result_data)

@common_buff_down_api.route("/common_buff_down/<int:is_push>", methods=['POST', 'GET'])
def DownAction(is_push):
    query = CommonBuff.query.order_by('id').all()
    result = []
    for i in query:
        result.append({
            "label": i.name,
            "value": int(i.id),
            "common_buff": json.loads(i.buff)
        })

    response = DownLoad('common_buff_project', result, is_push)

    return response